package com.example.capsule.controller;

import com.example.capsule.entity.Capsule;
import com.example.capsule.entity.Invitation;
import com.example.capsule.repository.CapsuleRepository;
import com.example.capsule.service.InvitationService;
import com.example.capsule.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/invitations")
@Tag(name = "邀请管理API", description = "时光胶囊邀请相关接口")
public class InvitationController {

    @Autowired
    private InvitationService invitationService;
    // 在控制器类中添加
    @Autowired
    private UserService userService;

    @Autowired
    private CapsuleRepository capsuleRepository;


    /**
     * 通过链接接受邀请并跳转
     */
    @GetMapping("/accept-by-link")
    @Operation(summary = "通过链接接受邀请", description = "通过邀请链接接受邀请并返回胶囊信息")
    public ResponseEntity<Map<String, Object>> acceptInvitationByLink(
            @Parameter(description = "邀请令牌") @RequestParam String token,
            @Parameter(description = "用户手机号") @RequestParam(required = false) String userPhone) {

        Map<String, Object> response = new HashMap<>();

        try {
            // 1. 验证token有效性
            Optional<Invitation> invitationOpt = invitationService.getInvitationByToken(token);
            if (invitationOpt.isEmpty()) {
                response.put("success", false);
                response.put("message", "邀请链接已失效");
                return ResponseEntity.badRequest().body(response);
            }

            Invitation invitation = invitationOpt.get();

            // 2. 检查是否过期
            if (invitation.isExpired()) {
                response.put("success", false);
                response.put("message", "邀请链接已过期");
                return ResponseEntity.badRequest().body(response);
            }

            // 3. 如果有用户手机号，处理邀请
            if (userPhone != null && !userPhone.trim().isEmpty()) {
                boolean acceptSuccess = invitationService.acceptInvitation(token, userPhone);
                if (!acceptSuccess) {
                    response.put("success", false);
                    response.put("message", "接受邀请失败");
                    return ResponseEntity.badRequest().body(response);
                }
            }

            // 4. 返回胶囊信息用于跳转
            response.put("success", true);
            response.put("capsuleId", invitation.getCapsuleId());
            response.put("token", token);
            response.put("message", "请跳转到胶囊页面查看内容");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "处理邀请链接失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取令牌信息
     */
    @GetMapping("/token-info")
    @Operation(summary = "获取令牌信息", description = "根据邀请令牌获取胶囊信息")
    public ResponseEntity<Map<String, Object>> getTokenInfo(
            @Parameter(description = "邀请令牌") @RequestParam String token) {

        Map<String, Object> response = new HashMap<>();

        try {
            Optional<Invitation> invitationOpt = invitationService.getInvitationByToken(token);
            if (invitationOpt.isEmpty()) {
                response.put("success", false);
                response.put("message", "邀请链接已失效");
                return ResponseEntity.badRequest().body(response);
            }

            Invitation invitation = invitationOpt.get();

            response.put("success", true);
            response.put("capsuleId", invitation.getCapsuleId());
            response.put("status", invitation.getStatus());
            response.put("expired", invitation.isExpired());
            response.put("createdAt", invitation.getCreatedAt());
            response.put("expiresAt", invitation.getExpiresAt());

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取令牌信息失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }



    /**
     * 创建邀请
     */
    @PostMapping("/create")
    @Operation(summary = "创建邀请", description = "为时光胶囊创建邀请")
    public ResponseEntity<Map<String, Object>> createInvitation(
            @RequestHeader("Authorization") String authHeader,
            @Parameter(description = "胶囊ID") @RequestParam Long capsuleId,
            @Parameter(description = "接收人手机号") @RequestParam String recipientPhone) {

        Map<String, Object> response = new HashMap<>();
        String userPhone = extractPhoneFromAuthHeader(authHeader);

        try {
            Invitation invitation = invitationService.createInvitation(capsuleId, userPhone, recipientPhone);

            response.put("success", true);
            response.put("message", "邀请创建成功");
            response.put("data", invitation);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 最小化修改接受邀请接口
    @PostMapping("/accept")
    @Operation(summary = "接受邀请", description = "通过邀请令牌接受时光胶囊邀请（需要登录）")
    public ResponseEntity<Map<String, Object>> acceptInvitation(
            @RequestHeader("Authorization") String authHeader,
            @RequestBody Map<String, String> request) {

        Map<String, Object> response = new HashMap<>();

        try {
            String userPhone = extractPhoneFromAuthHeader(authHeader);
            String token = request.get("token");

            if (token == null || token.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "邀请令牌不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            boolean success = invitationService.acceptInvitation(token, userPhone);

            // 总是返回胶囊信息，即使邀请已被处理
            Optional<Invitation> invitation = invitationService.getInvitationByToken(token);
            if (invitation.isPresent()) {
                Invitation inv = invitation.get();
                response.put("capsuleId", inv.getCapsuleId());
                response.put("status", inv.getStatus());

                // 检查胶囊是否存在且未过期
                Optional<Capsule> capsuleOpt = capsuleRepository.findById(inv.getCapsuleId());
                if (capsuleOpt.isPresent()) {
                    Capsule capsule = capsuleOpt.get();
                    response.put("canView", true);
                    response.put("capsuleTitle", capsule.getTitle());
                }
            }

            if (success) {
                response.put("success", true);
                response.put("message", "操作成功");
            } else {
                // 即使acceptInvitation返回false，也允许查看
                response.put("success", true);
                response.put("message", "邀请已处理，可以查看内容");
            }

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "处理邀请时发生错误：" + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }


    @PostMapping("/accept-public")
    @Operation(summary = "公开接受邀请", description = "通过邀请令牌接受时光胶囊邀请（公开接口）")
    public ResponseEntity<Map<String, Object>> acceptInvitationPublic(
            @RequestBody Map<String, String> request) {

        Map<String, Object> response = new HashMap<>();
        String token = request.get("token");
        String userPhone = request.get("userPhone");

        if (token == null || userPhone == null) {
            response.put("success", false);
            response.put("message", "令牌和手机号不能为空");
            return ResponseEntity.badRequest().body(response);
        }

        try {
            boolean success = invitationService.acceptInvitation(token, userPhone);

            if (success) {
                response.put("success", true);
                response.put("message", "邀请接受成功！");
            } else {
                response.put("success", false);
                response.put("message", "邀请已过期、无效或已被处理。");
            }
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "处理邀请时发生错误：" + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取当前用户的邀请列表
     */
    @GetMapping("/my-invitations")
    @Operation(summary = "我的邀请", description = "获取发送给当前用户的邀请列表")
    public ResponseEntity<Map<String, Object>> getMyInvitations(
            @RequestHeader("Authorization") String authHeader) {

        Map<String, Object> response = new HashMap<>();
        String userPhone = extractPhoneFromAuthHeader(authHeader);

        try {
            List<Invitation> invitations = invitationService.getUserInvitations(userPhone);

            response.put("success", true);
            response.put("data", invitations);
            response.put("count", invitations.size());
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取待处理邀请数量
     */
    @GetMapping("/pending-count")
    @Operation(summary = "待处理邀请数量", description = "获取当前用户待处理的邀请数量")
    public ResponseEntity<Map<String, Object>> getPendingInvitationCount(
            @RequestHeader("Authorization") String authHeader) {

        Map<String, Object> response = new HashMap<>();
        String userPhone = extractPhoneFromAuthHeader(authHeader);

        try {
            long count = invitationService.getPendingInvitationCount(userPhone);

            response.put("success", true);
            response.put("count", count);
            response.put("hasPending", count > 0);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取胶囊的邀请列表
     */
    @GetMapping("/capsule/{capsuleId}")
    @Operation(summary = "胶囊邀请列表", description = "获取指定胶囊的所有邀请")
    public ResponseEntity<Map<String, Object>> getCapsuleInvitations(
            @RequestHeader("Authorization") String authHeader,
            @Parameter(description = "胶囊ID") @PathVariable Long capsuleId) {

        Map<String, Object> response = new HashMap<>();
        String userPhone = extractPhoneFromAuthHeader(authHeader);

        try {
            List<Invitation> invitations = invitationService.getCapsuleInvitations(capsuleId, userPhone);

            response.put("success", true);
            response.put("data", invitations);
            response.put("count", invitations.size());
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 取消邀请
     */
    @DeleteMapping("/{invitationId}")
    @Operation(summary = "取消邀请", description = "取消指定的邀请")
    public ResponseEntity<Map<String, Object>> cancelInvitation(
            @RequestHeader("Authorization") String authHeader,
            @Parameter(description = "邀请ID") @PathVariable Long invitationId) {

        Map<String, Object> response = new HashMap<>();
        String userPhone = extractPhoneFromAuthHeader(authHeader);

        try {
            boolean success = invitationService.cancelInvitation(invitationId, userPhone);

            if (success) {
                response.put("success", true);
                response.put("message", "邀请已取消");
            } else {
                response.put("success", false);
                response.put("message", "取消邀请失败");
            }
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 重新发送邀请
     */
    @PostMapping("/{invitationId}/resend")
    @Operation(summary = "重新发送邀请", description = "重新发送指定的邀请")
    public ResponseEntity<Map<String, Object>> resendInvitation(
            @RequestHeader("Authorization") String authHeader,
            @Parameter(description = "邀请ID") @PathVariable Long invitationId) {

        Map<String, Object> response = new HashMap<>();
        String userPhone = extractPhoneFromAuthHeader(authHeader);

        try {
            boolean success = invitationService.resendInvitation(invitationId, userPhone);

            if (success) {
                response.put("success", true);
                response.put("message", "邀请已重新发送");
            } else {
                response.put("success", false);
                response.put("message", "重新发送邀请失败");
            }
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取邀请详情
     */
    @GetMapping("/{invitationId}")
    @Operation(summary = "邀请详情", description = "获取指定邀请的详细信息")
    public ResponseEntity<Map<String, Object>> getInvitationDetail(
            @RequestHeader("Authorization") String authHeader,
            @Parameter(description = "邀请ID") @PathVariable Long invitationId) {

        Map<String, Object> response = new HashMap<>();
        String userPhone = extractPhoneFromAuthHeader(authHeader);

        try {
            Invitation invitation = invitationService.getInvitationDetail(invitationId, userPhone)
                    .orElseThrow(() -> new RuntimeException("邀请不存在"));

            response.put("success", true);
            response.put("data", invitation);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 通过分享链接接受邀请（无需认证）
     */
    @PostMapping("/accept-by-token")
    @Operation(summary = "通过令牌接受邀请", description = "通过邀请令牌接受邀请（公开接口）")
    public ResponseEntity<Map<String, Object>> acceptInvitationByToken(
            @Parameter(description = "邀请令牌") @RequestParam String token,
            @Parameter(description = "用户手机号") @RequestParam String userPhone) {

        Map<String, Object> response = new HashMap<>();

        try {
            boolean success = invitationService.acceptInvitation(token, userPhone);

            if (success) {
                response.put("success", true);
                response.put("message", "邀请接受成功！");
            } else {
                response.put("success", false);
                response.put("message", "邀请已过期、无效或已被处理。");
            }
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "处理邀请时发生错误：" + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 从认证头中提取手机号
     */
    private String extractPhoneFromAuthHeader(String authHeader) {
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            return userService.getPhoneFromToken(token);
        }
        throw new RuntimeException("无效的认证信息");
    }

    // 在 InvitationController 中添加
    @GetMapping("/invitation-info")
    @Operation(summary = "获取邀请详细信息", description = "根据邀请令牌获取邀请的详细信息")
    public ResponseEntity<Map<String, Object>> getInvitationInfo(
            @Parameter(description = "邀请令牌") @RequestParam String token) {

        Map<String, Object> response = new HashMap<>();

        try {
            Optional<Invitation> invitationOpt = invitationService.getInvitationByToken(token);
            if (invitationOpt.isEmpty()) {
                response.put("success", false);
                response.put("message", "邀请链接已失效");
                return ResponseEntity.badRequest().body(response);
            }

            Invitation invitation = invitationOpt.get();

            // 获取胶囊信息
            Optional<Capsule> capsuleOpt = capsuleRepository.findById(invitation.getCapsuleId());

            response.put("success", true);
            response.put("intendedRecipient", invitation.getRecipientPhone());
            response.put("capsuleId", invitation.getCapsuleId());
            response.put("status", invitation.getStatus());
            response.put("expired", invitation.isExpired());
            response.put("createdAt", invitation.getCreatedAt());
            response.put("expiresAt", invitation.getExpiresAt());

            capsuleOpt.ifPresent(capsule -> {
                response.put("capsuleTitle", capsule.getTitle());
                response.put("senderPhone", capsule.getSenderPhone());
            });

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取邀请信息失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}